package czk.concrent.stampLock.stampLockPractice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/2 10:53
 */
public class StampedLockDemo2 {
    public static void main(String[] args) {
        StampedLock stampedLock = new StampedLock();
        // 先获得写锁
        new Thread(() -> {
            long writeLock = 0;
            try {
                writeLock = stampedLock.writeLock();
                System.out.println("获取写锁");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放
                stampedLock.unlock(writeLock);
            }

        }).start();
        // 在获取读锁
        new Thread(() -> {
            long readLock = 0;
            try {
                // 此时应该获取不到
                readLock = stampedLock.readLock();
                System.out.println("获取读锁了");
            } finally {
                stampedLock.unlock(readLock);
            }
        }).start();

    }
}
